package com.bys.controller;

import com.bys.service.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
public class PayController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private LoadBalancer loadBalancer;
    private final String getUrl = "EDU-CLOUD-RIBBON-PROVIDER";
    @GetMapping("/consumer/getById/{id}")
    public String getById(@PathVariable Integer id){
        return restTemplate.getForObject("http://"+getUrl +"/pay/string/getId/"+ id, String.class, id);
    }
    @GetMapping("/consumer/string/getId/{id}")
    public String loadGetById(@PathVariable Integer id){
        List<ServiceInstance> instances = discoveryClient.getInstances(getUrl);
        if(instances ==null || instances.size() <= 0){
            throw new RuntimeException("服务不存在");
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/pay/string/getId/"+ id,String.class);

    }
}
